<template>
    <custom-page-box>
        <div class="need-manage-audit-container">
            <div class="search-box">
                <a-form-model layout="inline" :model="form">
                    <a-form-model-item prop="keyword" class="keyword-input">
                        <a-input v-model="form.keyword" placeholder="标题"></a-input>
                    </a-form-model-item>
                    <a-form-model-item prop="type" class="type-select">
                        <a-cascader
                            v-model="form.type"
                            :options="treeData"
                            placeholder="类型"
                            change-on-select
                            :field-names="{
                                label: 'name',
                                value: 'id',
                                children: 'children'
                            }"
                        />
                    </a-form-model-item>
                    <a-form-model-item prop="status" class="status-select">
                        <a-select v-model="form.status" placeholder="审核状态" :allowClear="true">
                            <a-select-option :value="0">待审核</a-select-option>
                            <a-select-option :value="1">已通过</a-select-option>
                            <a-select-option :value="2">已驳回</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item prop="time" class="time-arr">
                        <a-range-picker :placeholder="['发起开始时间', '结束时间']" @change="onChange" />
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-button @click="searchTable">搜索</a-button>
                    </a-form-model-item>
                </a-form-model>
            </div>
            <div class="table">
                <a-table
                    :data-source="tableData"
                    rowKey="id"
                    :pagination="false"
                    :row-selection="{
                        selectedRows: selectedRows,
                        selectedRowKeys: selectedRowKeys,
                        onChange: onSelectChange
                    }"
                    :scroll="{ x: width, y: height }"
                >
                    <a-table-column key="index" title="序号" data-index="index" width="80px">
                        <template slot-scope="text, record, index">
                            {{ (pageIndex - 1) * pageSize + index + 1 }}
                        </template>
                    </a-table-column>
                    <a-table-column title="标题" data-index="title" width="100px" :ellipsis="true">
                        <template slot-scope="text, record">
                            <a-button type="link" @click="toDetail(record)">
                                {{ record.title }}
                            </a-button>
                        </template>
                    </a-table-column>
                    <a-table-column
                        key="enterDemandType"
                        title="类型"
                        data-index="enterDemandType"
                        width="140px"
                        :ellipsis="true"
                    >
                        <template slot-scope="text, record">
                            <span v-if="record.enterDemandType === 1">房源</span>
                            <span v-if="record.enterDemandType === 2">地块</span>
                            <span v-if="record.enterDemandType === 3">人才</span>
                            <span v-if="record.enterDemandType === 4">产品</span>
                            <span
                                v-if="record.enterDemandType === 5"
                            >服务{{ record.typeName ? '/' + record.typeName : '' }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column
                        key="companyName"
                        title="公司名称"
                        data-index="companyName"
                        width="120px"
                        :ellipsis="true"
                    />
                    <a-table-column
                        key="auditState"
                        title="审核状态"
                        data-index="auditState"
                        width="100px"
                        :ellipsis="true"
                    >
                        <template slot-scope="text, record">
                            <span v-if="record.auditState === 1" class="green-txt">已通过</span>
                            <span v-else-if="record.auditState === 2" class="red-txt">已驳回</span>
                            <span v-else class="blue-txt">待审核</span>
                        </template>
                    </a-table-column>
                    <a-table-column
                        key="createTime"
                        title="发起时间"
                        data-index="createTime"
                        width="150px"
                        :ellipsis="true"
                    />
                    <a-table-column
                        key="reviewTime"
                        title="审核时间"
                        data-index="reviewTime"
                        width="150px"
                        :ellipsis="true"
                    />
                    <a-table-column key="reviewer" title="审核人" data-index="reviewer" width="80px" :ellipsis="true">
                    </a-table-column>
                    <a-table-column key="c" title="操作" width="100px">
                        <template slot-scope="text">
                            <a-button class="green" v-if="text.auditState === 0" @click="toDetail(text)">审核</a-button>
                        </template>
                    </a-table-column>
                </a-table>
            </div>
        </div>

        <custom-pagination :total="Number(total)" :page.sync="pageIndex" :limit.sync="pageSize" @pagination="getTable">
            <div class="pagination-tool">
                <p>
                    已选<span class="num">{{ selectedRows.length }}</span>条
                </p>
                <a-button @click="toPass()" :disabled="disablePass"> 批量通过 </a-button>
                <a-button @click="toReject()" :disabled="disableReject"> 批量驳回 </a-button>
            </div>
        </custom-pagination>
        <a-modal title="审批驳回" :visible="show" @ok="handleOk" @cancel="handleModelCancel" class="reject-model">
            <a-form :form="auditForm" ref="ruleForm" layout="horizontal" :key="renderKey">
                <a-form-item label="驳回原因">
                    <a-textarea
                        placeholder="请输入驳回原因"
                        :maxLength="200"
                        :rows="4"
                        v-decorator="[
                            'auditContent',
                            {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入驳回原因(200字以内)'
                                    }
                                ]
                            }
                        ]"
                    />
                </a-form-item>
                <a-form-item extra="支持扩展名：.jpg,.jpeg,.png,大小不超过6M">
                    <a-upload
                        v-decorator="[
                            'upload',
                            {
                                getValueFromEvent: normFile
                            }
                        ]"
                        :action="$staticUrl"
                        list-type="picture"
                        :data="uploadData"
                        :before-upload="beforeUpload"
                        :remove="handleRemove"
                        @change="handleChange"
                    >
                        <a-button v-if="fileList.length < 9"> <a-icon type="upload" /> 上传文件 </a-button>
                    </a-upload>
                </a-form-item>
            </a-form>
        </a-modal>
    </custom-page-box>
</template>

<script>
import { getUUID } from '@/plugins/tools'

export default {
    name: 'NeedManageAudit',
    data () {
        return {
            total: 0,
            pageIndex: 1,
            pageSize: 10,
            tableData: [],
            show: false,
            modalData: {},
            form: {
                keyword: '',
                type: [],
                status: undefined,
                time: []
            },
            selectedRows: [],
            selectedRowKeys: [],
            width: 1000,
            height: 500,
            auditForm: this.$form.createForm(this, { name: 'coordinated' }),
            uploadData: {
                signature: '',
                'x-cos-security-token': '',
                'Content-Type': '',
                key: '',
                dir: '',
                host: ''
            },
            fileList: [],
            typeList: ['image/jpeg', 'image/png', 'image/bmp'],
            path: '/need-audit/img/',
            sourceList: [],
            renderKey: 0,
            treeData: []
        }
    },
    computed: {
        disablePass () {
            if (!this.selectedRows.length) return true
            const arr = this.selectedRows.filter(item => ![0].includes(item.auditState))
            return !!arr.length
        },
        disableReject () {
            if (!this.selectedRows.length) return true
            const arr = this.selectedRows.filter(item => ![0].includes(item.auditState))
            return !!arr.length
        }
    },
    created () {
        this.getTable()
        this.getTree()
    },
    mounted () {
        const arr = document.getElementsByClassName('table')
        if (arr[0]) {
            this.width = arr[0].offsetWidth - 17
            this.height = arr[0].offsetHeight - 59 + 17
        }
    },
    methods: {
        searchTable () {
            this.pageIndex = 1
            this.getTable()
        },
        async getTree () {
            const res = await this.$ApiServer['operationConfig/getTree']()
            if (res.code === 200) {
                const add = (list) => {
                    list.forEach((item) => {
                        item.scopedSlots = { title: 'custom' }
                        if (item.children && item.children.length) {
                            item.children = add(item.children)
                        } else {
                            item.children = []
                        }
                    })
                    return list
                }
                this.treeData = add(res.data)
                const filterStatus = (list) => {
                    return list.filter((item) => {
                        if (item.children) {
                            item.children = filterStatus(item.children)
                        }
                        return item.status
                    })
                }
                this.treeData = filterStatus(this.treeData)
                this.treeData.forEach((item) => {
                    if (item.children) {
                        item.children.forEach((it) => {
                            delete it.children
                        })
                    }
                })
                this.treeData = [
                    {
                        id: 1,
                        name: '房源'
                    },
                    {
                        id: 2,
                        name: '地块'
                    },
                    {
                        id: 3,
                        name: '人才'
                    },
                    {
                        id: 4,
                        name: '产品'
                    },
                    {
                        id: 5,
                        name: '服务',
                        children: this.treeData
                    }
                ]
            }
        },
        async getTable () {
            const { keyword, type, status, time } = this.form
            const res = await this.$ApiServer['need/list/audit']({
                currentPage: this.pageIndex,
                pageSize: this.pageSize,
                keyword,
                enterDemandType: type.length ? type[0] : '',
                auditState: status,
                startTime: time[0],
                endTime: time[1],
                type: type.length ? (type[0] === 5 ? type[type.length - 1] : '') : ''
            })
            if (res.code === 200) {
                this.tableData = res.data.records || []
                this.total = res.data.total
            } else {
                this.$message.error(res.message)
            }
        },
        onChange (date, dateString) {
            this.form.time = dateString
        },
        toPass () {
            this.$confirm({
                title: '提示',
                content: '是否确认通过本次认证审核',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    const res = await this.$ApiServer['need/pass/audit']({
                        idList: this.selectedRowKeys
                    })
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.getTable()
                    } else {
                        this.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        toReject () {
            this.show = true
        },
        handleOk () {
            this.auditForm.validateFields((err, values) => {
                let auditImgList = []
                if (this.sourceList.length) {
                    auditImgList = this.sourceList.map(item => item.url)
                }
                if (!err) {
                    this.$ApiServer['need/reject/audit']({
                        idList: this.selectedRowKeys,
                        imgList: auditImgList,
                        message: values.auditContent
                    }).then((res) => {
                        if (res.code === 200) {
                            this.$message.success('操作成功')
                            this.selectedRows = []
                            this.selectedRowKeys = []
                            this.getTable()
                            this.handleModelCancel()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            })
        },
        handleModelCancel () {
            this.visible = false
            this.sourceList = []
            this.fileList = []
            this.$refs.ruleForm.resetFields()
            this.renderKey++
        },
        beforeUpload (file) {
            return new Promise((resolve, reject) => {
                if (!this.typeList.includes(file.type)) {
                    this.$message.error('上传图片格式不对!')
                    return false
                }
                const isLt6M = file.size / 1024 / 1024 < 6
                if (!isLt6M) {
                    this.$message.error('图片大小不能超过6M!')
                    return false
                }
                const _path = '/' + this.path + '/' + this.$service.dateFormatter('yyyy-MM-dd') + '/'
                this.$service
                    .getAuthor({ Method: 'POST', Pathname: '/' })
                    .then((info) => {
                        this.uploadData.signature = info.Authorization
                        this.uploadData['x-cos-security-token'] = info.XCosSecurityToken
                        this.uploadData['Content-Type'] = ''
                        this.uploadData.key = _path + getUUID() + '.' + file.name.replace(/,/g, '').split('.').pop()
                        this.uploadData.dir = this.path
                        this.uploadData.host = this.$staticUrl
                        resolve(true)
                    })
                    .catch((err) => {
                        return reject(new Error(err))
                    })
            })
        },
        handleChange ({ file, fileList }) {
            if (file.status === 'uploading') {
                return
            }
            if (file.status === 'done') {
                this.sourceList.push({
                    _id: file.uid,
                    url: this.uploadData.key
                })
                this.fileList = fileList
            }
        },
        handleRemove (file) {
            const index = this.sourceList.findIndex(item => item._id === file.uid)
            const num = this.fileList.findIndex(item => item.uid === file.uid)
            this.sourceList.splice(index, 1)
            this.fileList.splice(num, 1)
        },
        normFile (e) {
            if (Array.isArray(e)) {
                return e
            }
            return e && e.fileList
        },
        toDetail (row) {
            let name = ''
            switch (row.enterDemandType) {
            case 1:
                name = 'houses'
                break
            case 2:
                name = 'plot'
                break
            case 3:
                name = 'talents'
                break
            case 4:
                name = 'product'
                break
            case 5:
                name = 'service'
                break
            }
            console.log(name)
            this.$router.push({
                path: `/need-manage/audit/${name}`,
                query: {
                    id: row.id,
                    d: 'd'
                }
            })
        },
        onSelectChange (selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        }
    }
}
</script>

<style scoped lang="less">
.need-manage-audit-container {
    padding: 10px 20px;
    background-color: #fff;
    overflow: hidden;
    border-radius: 6px;
    margin-bottom: 10px;
    .search-box {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        background: #fff;
        padding: 10px 20px;
        margin-bottom: 10px;
        border: 1px solid #e3e3e3;
        .keyword-input {
            ::v-deep {
                .ant-input {
                    width: 120px;
                }
            }
        }
        .type-select,
        .status-select {
            ::v-deep {
                .ant-select {
                    width: 120px;
                }
            }
        }
        ::v-deep {
            .ant-form-item-control {
                line-height: 32px;
            }
        }
        .time-arr {
            height: 32px;
            width: 260px;
            ::v-deep {
                .ant-calendar-picker-input {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                }
            }
        }
        button {
            box-sizing: border-box;
            height: 32px;
            line-height: 32px;
            color: #fff;
            background: @primary-color;
            border-radius: 2px;
            border-color: @primary-color;
        }
    }
    .table {
        height: calc(100vh - 60px - 10px - 155px);
        background: #fff;
    }
}
::v-deep {
    .pagination-tool {
        padding-left: 20px;
        p:first-child {
            font-size: 20px;
            margin-right: 40px;
            position: relative;
            &:after {
                content: '';
                display: block;
                width: 1px;
                height: 40px;
                background-color: #f3f3f3;
                position: absolute;
                right: -20px;
                top: 50%;
                transform: translateY(-50%);
            }
        }
        .num {
            font-size: 32px !important;
        }
        button {
            width: 100px;
            height: 36px;
            background: #ffffff;
            border: 1px solid #666666;
            border-radius: 2px;
        }
    }
}
::v-deep {
    .ant-btn-link {
        color: @primary-color !important;
        span {
            display: block;
            overflow: hidden;
            width: 100%;
            text-overflow: ellipsis;
            text-decoration: underline;
        }
    }
}
</style>
